# -*- coding: utf-8 -*-
class Loan < ActiveRecord::Base
  has_many :loan_details ,:dependent => :destroy      #级联删除子表
  has_many :loan_deliveries ,:dependent => :destroy      #级联删除子表

  belongs_to :customer
  belongs_to :employee      #制单人员
  belongs_to :department
  belongs_to :company
  belongs_to :sales, :class_name => 'Employee', :foreign_key => 'sales_id'      #此订单的销售员。
  belongs_to :auditor, :class_name => 'Employee', :foreign_key => 'auditor_id'

  def self.findAllLoans  conditionsStr,conditionsHash,paramsHash
    begin
      find(
        :all,
        :conditions => [conditionsStr,conditionsHash],
        :include => [:employee,:department,:customer,:auditor,:sales,:loan_details],
        :offset => paramsHash[:offset],
        :limit => paramsHash[:limit],
        :order => 'loans.updated_at DESC'
      )
    rescue Exception => e
      puts "Fuck From findAllSaleOrders"
      logger.info e
    end
  end

  def self.countAllLoans  conditionsStr,conditionsHash
    begin
      count(
        :all,
        :include=>[:loan_details],
        :conditions => [conditionsStr,conditionsHash]
      )
    rescue Exception => e
      logger.info "countAllLoans..............."
      logger.info e
    end
  end

  #对比销售与出库的数量差别，这里只把已经撤消的排除在外，其它的状态比较申请状态的入库，我们都计算在内。所以在很多地方要把所有的申请都排除在外时，操作才可以顺畅。
  #这里是检查不出另一种情况的，就是出库比销售还多的情况，这里只能查询出入库比采购少的情况。
  scope :diff_loan_delivery, lambda { |loanId| joins("lo left join loan_details lod on lo.id = lod.loan_id
                                  left join (select sum(ldd.quantity) quantity,ldd.product_id from loan_deliveries ld left join loan_delivery_details ldd on ld.id = ldd.loan_delivery_id where ld.loan_id = #{loanId} AND ld.auditing_status != '通过撤消' GROUP BY ldd.product_id) outterldd on outterldd.product_id = lod.product_id
      ").where("lo.id = ?",loanId).select("lod.product_id,sum(lod.quantity) lod_quantity,ifnull(sum(outterldd.quantity),0) ldd_quantity").group("lod.product_id").having("lod_quantity - ldd_quantity != 0") }

  #对比销售与出库的数量差别，这里只把已经撤消的排除在外，其它的状态比较申请状态的入库，我们都计算在内。所以在很多地方要把所有的申请都排除在外时，操作才可以顺畅。
  #这里是检查不出另一种情况的，就是出库比销售还多的情况，这里只能查询出入库比采购少的情况。
  scope :diff_loan_returned, lambda { |loanId| joins("lo left join loan_details lod on lo.id = lod.loan_id
                                  left join (select sum(lrd.quantity) quantity,lrd.product_id from loan_returneds lr left join loan_returned_details lrd on lr.id = lrd.loan_returned_id where lr.loan_id = #{loanId} AND lr.auditing_status != '通过撤消' GROUP BY lrd.product_id) outterlrd on outterlrd.product_id = lod.product_id
      ").where("lo.id = ?",loanId).select("lod.product_id,sum(lod.quantity) lod_quantity,ifnull(sum(outterlrd.quantity),0) lrd_quantity").group("lod.product_id").having("lod_quantity - lrd_quantity != 0") }

end
